package serv

import (
	"context"
	"errors"
	"fmt"
	"generate_grom_mode_and_dao/service/genertategrom/api/internal/svc"
	"github.com/tal-tech/go-zero/core/logx"
	"strings"
)

type (
	MakeService interface {
		Start()
	}

	defaultMakeService struct {
		logx.Logger
		ctx    context.Context
		svcCtx *svc.ServiceContext
	}
)

func NewMakeService(ctx context.Context, svcCtx *svc.ServiceContext) *defaultMakeService {
	return &defaultMakeService{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

/**
 *  Start
 *  @Description: 开始生成
 *  @receiver s
 *  @return error
 */
func (s defaultMakeService) Start() error {

	tableNames := s.svcCtx.Config.GenerateModel.TableNames
	if len(tableNames) == 0 {
		panic("未填写表名,请填写表名")
	}
	tableNamesString := "'" + strings.Join(tableNames, "','") + "'"
	//if !strings.Contains(s.svcCtx.Config.MysqlGenerateGorm.DataSource, s.svcCtx.Config.MysqlGenerateGorm.DatabaseName) {
	//	return errors.New("yaml 文件中 DatabaseName 和 DataSource 中配置的数据库名不一致")
	//}
	//获取数据库的名字
	database, err := s.svcCtx.DatabaseDao.GetCurrentDatabase()
	if nil != err {
		return err
	}
	tables, err := s.svcCtx.TableDao.GetTables(tableNamesString, database)
	if nil != err {
		return err
	}
	errSlice := make([]string, 0)
	serviceMake := NewTouchModelService(s.ctx, s.svcCtx)
	serviceDao := NewGenerateDaoService(s.ctx, s.svcCtx)
	serviceEnum := NewGenerateEnumService(s.ctx, s.svcCtx)

	serviceXorm := NewGenerateXormModelService(s.ctx, s.svcCtx)
	//info, err := s.svcCtx.DatabaseDao.GetAllColumnInfo("")

	fmt.Println(err)
	//fmt.Println(info)

	for _, table := range *tables {
		fields, err := s.svcCtx.TableFieldsDao.GetTablesFields(table.Name)
		if nil != err {
			errSlice = append(errSlice, table.Name+"未查询字段到数据: "+err.Error())
			continue
		}
		if s.svcCtx.Config.GenerateModel.GenerateModel {
			err = serviceMake.Create(table, fields)
			if nil != err {
				errSlice = append(errSlice, table.Name+"生成model失败: "+err.Error())
				continue
			}
		} else {
			fmt.Println("不需要生成model文件")
		}
		if s.svcCtx.Config.GenerateModel.GenerateDao {
			err = serviceDao.Create(table, fields)
			if nil != err {
				errSlice = append(errSlice, table.Name+"生成dao文件失败: "+err.Error())
				continue
			}
		} else {
			fmt.Println("不需要生成dao文件")
		}
		if s.svcCtx.Config.GenerateModel.GenerateEnum {
			err = serviceEnum.Create(table, fields)
			if nil != err {
				errSlice = append(errSlice, table.Name+"生成dao文件失败: "+err.Error())
				continue
			}
		} else {
			fmt.Println("不需要生成enum文件")
		}

		err = serviceXorm.Create(table, fields)
		if nil != err {
			errSlice = append(errSlice, table.Name+"生成dao文件失败: "+err.Error())
			continue
		}

	}
	if len(errSlice) != 0 {
		fmt.Println("errSlice: ", errSlice)
		return errors.New("操作失败")
	}
	return nil
}
